import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {AtIcon, AtList, AtListItem} from 'taro-ui'
import {View, Text, Image, Picker} from '@tarojs/components'
import {CHILD_SELLER_LIST, DISTRIBUTION_ORDER_SUM_DATA, RESOURCE_URL} from '../../constants/api'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {newHttp} from "../../utils/request";
import Water from "../components/water-mark";
import './customer.scss'

interface stateType {
  infoData: any
  tabs: any
  orderList: any
  todayTime: number
  beforeTime: number
  sevenDayAfter: number
  tomorrowTime: number
  searchResult: any
  timeTabIndex: number
  isOpenTime: boolean
  info: any
}

class Search extends Component {
  state: stateType = {
    infoData: '',
    isOpenTime: false,
    searchResult: [],
    todayTime: 0,
    beforeTime: 0,
    sevenDayAfter: 0,
    tomorrowTime: 0,
    timeTabIndex: 0,
    info: {
      money: 0,
      num: 0,
      earningsMoney: 0
    }
  }
  page = 1
  total = 0
  length = 10

  searchConfirm() {
    this.page = 1
    this.search(this.page)
  }
  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }
  async componentDidShow() {
    this.page = 1
    vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const n = new Date()
    const todayTime = n.getTime()
    const beforeTime = n.getTime() - (24 * 60 * 60 * 1000)
    const tomorrowTime = n.getTime() + (24 * 60 * 60 * 1000)
    const sevenDayAfter = n.getTime() + (24 * 60 * 60 * 1000 * 6)
    const active = Taro.getCurrentInstance().router.params.active || ''
    let dateStart = Taro.getCurrentInstance().router.params.search_date_start || ''
    if (active == 1){
      let timeTabIndex = 0
      let dateEnd
      if (dateStart === this.getDate(todayTime)) {
        timeTabIndex = 1
        dateEnd = dateStart
      } else if (dateStart === this.getDate(beforeTime)) {
        timeTabIndex = 2
        dateEnd = dateStart
      } else if (this.getDate(todayTime) <= dateStart && dateStart <= this.getDate(sevenDayAfter - (24 * 60 * 60 * 1000))) {
        timeTabIndex = 3
        dateStart = this.getDate(todayTime)
        dateEnd = this.getDate(sevenDayAfter - (24 * 60 * 60 * 1000))
      } else {
        dateStart = ''
      }
      await this.setStateSync({ timeTabIndex, dateStart, dateEnd })
    }
    this.setState({todayTime, beforeTime, sevenDayAfter, tomorrowTime})
    await this.search(this.page)
  }

  async onReachBottom() {
    this.page++
    await this.search(this.page)
  }

  async search(page) {
    Taro.showLoading({title: "加载中..."})
    const ret = await this.getSearchData(page);
    Taro.hideLoading()
    if (ret && ret.length > 0) {
      if (page === 1) {
        this.setState({searchResult: ret})
      } else if (page > 1) {
        const oldData = this.state.searchResult;
        this.setState({searchResult: [...oldData, ...ret]})
      }
    } else {
      if (page === 1) {
        this.setState({searchResult: []})
      }
    }
  }

  async getSearchData(page) {
    if (typeof page != "number") {
      page = this.page + 1
    }
    const {dateStart, dateEnd} = this.state
    const data = {
      page,
      length: 10,
      child_flag: 1,
      search_date_start: dateStart,
      search_date_end: dateEnd
    }
    const info = await newHttp.catchGet(DISTRIBUTION_ORDER_SUM_DATA, data)
    let result = await newHttp.catchGet(CHILD_SELLER_LIST, data)
    this.setState({info: result, infoData: info})
    if (!result) {
      return false;
    } else {
      result = result.list
    }
    return result || []
  }

  onDateChange(type, e) {
    if (type === 'dateStart') {
      this.setState({dateStart: e.detail.value})
    }
    if (type === 'dateEnd') {
      this.setState({dateEnd: e.detail.value})
    }
  }

  customTime() {
    this.setState({isOpenTime: !this.state.isOpenTime})
  }

  sureBtn() {
    const {dateStart, dateEnd, todayTime, beforeTime, sevenDayAfter, tomorrowTime} = this.state
    this.setState({isOpenTime: false})
    if (dateStart && dateEnd) {
      let timeTabIndex = -1
      if ((dateStart === this.getDate(todayTime) && dateEnd === this.getDate(tomorrowTime)) || dateStart === this.getDate(todayTime) && dateEnd === this.getDate(todayTime)) {
        timeTabIndex = 1
      } else if (dateStart === this.getDate(beforeTime) && dateEnd === this.getDate(todayTime)) {
        timeTabIndex = 2
      } else if (dateStart === this.getDate(todayTime) && (dateEnd <= this.getDate(sevenDayAfter) && dateEnd > this.getDate(todayTime + (24 * 60 * 60 * 1000)))) {
        timeTabIndex = 3
      }
      this.setState({timeTabIndex})
    }
    this.searchConfirm()
  }

  getDate(time) {
    const newTimeDate = new Date(time)
    let now = ''
    now += newTimeDate.getFullYear() + '-'
    now += newTimeDate.getMonth() + 1 < 10 ? '0' + (newTimeDate.getMonth() + 1) : newTimeDate.getMonth() + 1
    now += '-'
    now += newTimeDate.getDate() < 10 ? '0' + newTimeDate.getDate() : newTimeDate.getDate()
    return now
  }

  changeTab(val) {
    const {timeTabIndex, todayTime, beforeTime, sevenDayAfter} = this.state
    if (val !== timeTabIndex) {
      if (val === 1) {
        this.setState({
          timeTabIndex: val,
          dateStart: this.getDate(todayTime),
          dateEnd: this.getDate(todayTime + (24 * 60 * 60 * 1000))
        }, async () => {
          this.searchConfirm()
        })
      } else if (val === 2) {
        this.setState({
          timeTabIndex: val,
          dateStart: this.getDate(beforeTime),
          dateEnd: this.getDate(beforeTime)
        }, async () => {
          this.searchConfirm()
        })
      } else if (val === 3) {
        this.setState({
          timeTabIndex: val,
          dateStart: this.getDate(todayTime),
          dateEnd: this.getDate(sevenDayAfter)
        }, async () => {
          this.searchConfirm()
        })
      } else {
        this.setState({timeTabIndex: val, dateStart: '', dateEnd: ''}, async () => {
          this.searchConfirm()
        })
      }
    }
  }

  jumpOther(url, type, childSellerId){
    console.log(childSellerId)
    const {dateStart, dateEnd, timeTabIndex} = this.state
    url += `?timeTabIndex=${timeTabIndex}&dateStart=${dateStart}&dateEnd=${dateEnd}&type=${type}&childSellerId=${childSellerId}`
    Taro.navigateTo({url})
  }

  render() {
    const {searchResult, timeTabIndex, infoData, isOpenTime, dateStart, dateEnd, info} = this.state
    return (
      <View className='promotionOrderRoot myInvite-promotionOrderRoot'>
        <GzhAuth />
        <Water />
        <View className='search-top'>
          <View className='time-filter-item-wrapper'>
            <View className='time-filter-item'>
              <View onClick={this.changeTab.bind(this, 0)}
                className={`time-filter-items ${timeTabIndex === 0 && 'time-active'}`}
              >全部</View>
              <View onClick={this.changeTab.bind(this, 1)}
                className={`time-filter-items ${timeTabIndex === 1 && 'time-active'}`}
              >今日</View>
              <View onClick={this.changeTab.bind(this, 2)}
                className={`time-filter-items ${timeTabIndex === 2 && 'time-active'}`}
              >昨日</View>
              <View onClick={this.changeTab.bind(this, 3)}
                className={`time-filter-items ${timeTabIndex === 3 && 'time-active'}`}
              >近7日</View>
            </View>
            <View className='custom-time' onClick={this.customTime.bind(this)}>自定义时间<AtIcon
              value={isOpenTime ? 'chevron-up' : 'chevron-down'} size='12' color='#ccc'
            /></View>
          </View>
          {isOpenTime && <View className='time-picker-choice'>
            <Picker className='time-picker-choice-picker' mode='date'
              onChange={this.onDateChange.bind(this, 'dateStart')}
            >
              <AtList>
                <AtListItem title='开始日期' extraText={dateStart} />
              </AtList>
            </Picker>
            <Picker className='time-picker-choice-picker' mode='date'
              onChange={this.onDateChange.bind(this, 'dateEnd')}
            >
              <AtList>
                <AtListItem title='结束日期' extraText={dateEnd} />
              </AtList>
            </Picker>
          </View>}
          {isOpenTime && <View className='sure-btn' onClick={this.sureBtn.bind(this)}>确定</View>}
        </View>
        {searchResult && searchResult.length > 0 && <View className='promotion-order-info-wrapper promotion-order-info-wrapper-my-invite'>
          <View className='promotion-order-top-info'>共<Text className='promotion-order-nums'>{infoData.child_seller_num}</Text>个邀请,获得邀请奖励<Text className='promotion-order-nums'>{infoData.money}</Text>（含待结算{infoData.earningsMoney}元）</View>
          <View className='list-container'>
            {searchResult.map(item => <View onClick={this.jumpOther.bind(this, '/main/order/promotionOrder', 'invite', item.id)} className='salesman-customer van-cell van-cell--center'>
                <View className='van-cell__value van-cell__value--alone'>
                  <View className={`salesman-avatar ${!item.effective && 'salesman-avatar--disabled'}`}>
                    <Image className='salesman-avatar__img' src={item.photo || `${RESOURCE_URL}/upload/images/20211120/1637398013770_87.png`} />
                  </View>
                  <View className='my-invite-items'>
                    <View className='salesman-customer__info-block'>
                      <View className='salesman-customer__info'>
                        <View className='salesman-customer__info-top'>
                          <Text className='salesman-customer__info-name copy'>{item.real_name}</Text>
                        </View>
                        <View className='salesman-customer__info--bill'>
                          <View className='text'>我的邀请奖励：<Text className='text-num'>{item.money}</Text></View>
                        </View>
                      </View>
                    </View>
                    <View>
                      <AtIcon value='chevron-right' size='20' color='#999' customStyle='line-height: initial;vertical-align: middle !important;' />
                    </View>
                  </View>
                </View>
              </View>
            ) }
          </View>
        </View>}
        {isOpenTime && <View className='open-time-over-layout'>
          <View className='over-layout' onClick={() => {
            this.setState({isOpenTime: !isOpenTime})
          }}
          />
        </View>}
        {searchResult.length <= 0 && <View className='listNull'>
          <Image src={`${RESOURCE_URL}/upload/images/20211112/1636708674979_153.png`} mode='widthFix' />
          <View className='text'>暂无数据</View>
        </View>}
        <View style='height: 30px;'></View>
      </View>
    )
  }
}

export default Search as ComponentClass
